package com.bdzl.repay.common.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * fl_loanbase数据源配置类
 */
@Configuration
@Slf4j
@MapperScan(basePackages = {"com.bdzl.repay.dao"}, sqlSessionTemplateRef = "flLoanBaseSqlSessionTemplate")
public class FlLoanbaseRepayDruidDBConfig {
    // 读取数据库连接信息
    @Value("${spring.datasource.flloanbase.url}")
    private String dbUrl;
    @Value("${spring.datasource.flloanbase.username}")
    private String username;
    @Value("${spring.datasource.flloanbase.password}")
    private String password;
    @Value("${spring.datasource.flloanbase.driverClassName}")
    private String driverClassName;
    // 初始化、最小连接池数
    @Value("${spring.datasource.initialSize}")
    private int initialSize;
    @Value("${spring.datasource.minIdle}")
    private int minIdle;
    @Value("${spring.datasource.maxWait}")
    // 读取配置获取连接等待超时的时间、配置获取连接间隔检测、一个连接在池中最小生存的时间，单位毫秒
    private int maxWait;
    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;
    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;
    // 读取配置监控统计拦截的filters，去掉后监控界面sql无法统计，'wall'用于防sql注入
    @Value("${spring.datasource.filters}")
    private String filters;
    @Value("{spring.datasource.connectionProperties}")
    private String connectionProperties;

    //mapper文件路径
    @Value("${mybatis.mapper-locations}")
    String mapperLocations;


    @Bean(name = "flLoanBaseDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.flloanbase")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(this.dbUrl);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setInitialSize(initialSize);
        dataSource.setMinIdle(minIdle);
        dataSource.setMaxWait(maxWait);
        dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        try {
            dataSource.setFilters(filters);
        } catch (SQLException e) {
            log.error("druid configuration initialization filter", e);
        }
        dataSource.setConnectionProperties(connectionProperties);
        return dataSource;
    }

    @Bean(name = "flLoanBaseTransactionManager")
    public DataSourceTransactionManager setTransactionManager(@Qualifier("flLoanBaseDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "flLoanBaseSqlSessionFactory")
    @ConfigurationProperties(prefix = "flloanbase")
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("flLoanBaseDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocations));
        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return bean.getObject();
    }


    @Bean(name = "flLoanBaseSqlSessionTemplate")
    public SqlSessionTemplate setSqlSessionTemplate(
            @Qualifier("flLoanBaseSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


    @Bean
    public PlatformTransactionManager flLoanBaseTransactionManager(@Qualifier("flLoanBaseDataSource") DataSource prodDataSource) {
        return new DataSourceTransactionManager(prodDataSource);
    }
}
